import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    private Socket socket = null;//这里创建的就是 socket,不是ServerSocket

    public TCPEchoClient(String serverIP,int serverPort) throws IOException {
        //这样的构造过程,就会和服务器建立 TCP 连接
        //建立连接的流程,都是系统内核完成的
        socket = new Socket(serverIP,serverPort);
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {

            Scanner scannerNetwork = new Scanner(inputStream);

            while (true){
                //1.从控制台读取数据
                System.out.println("输入要发送的数据:");
                String request = scanner.next();

                //2.请求发送给服务器
                //这里发送的请求要带有换行(\n) 和服务器是要对应的
                request+="\n";
                outputStream.write(request.getBytes());

                //3.从服务器读取到响应
                if (!scannerNetwork.hasNext()){
                    break;
                }
                String response = scannerNetwork.next();

                //4.把响应显示到控制台上
                System.out.println(response);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9090);
        client.start();

    }
}
